package com.frank.oj.config;

import com.frank.oj.constant.Constants;
import com.frank.oj.interceptor.AccessInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import javax.xml.soap.SAAJResult;
import java.io.File;

/**
 * @author frank
 * @Date 2024/3/22
 */
@Configuration
public class WebMVCConfig implements WebMvcConfigurer {

    /**
     * 跨域
     *
     * @param registry 跨域注册表
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }

    /**
     * 图片访问：配置静态资源处理器。当客户端请求这些资源时，Spring MVC能够正确地将请求路由到对应的资源。
     *
     * @param registry 拦截器注册表
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射静态资源URL路径
        registry.addResourceHandler(Constants.File.IMG_API.getPath() + "/**", Constants.File.FILE_API.getPath() + "/**")
                // 指定静态资源文件的实际位置
                .addResourceLocations("file:" + Constants.File.USER_AVATAR_FOLDER.getPath() + File.separator,
                        "file:" + Constants.File.GROUP_AVATAR_FOLDER.getPath() + File.separator,
                        "file:" + Constants.File.MARKDOWN_FILE_FOLDER.getPath() + File.separator,
                        "file:" + Constants.File.HOME_CAROUSEL_FOLDER.getPath() + File.separator,
                        "file:" + Constants.File.PROBLEM_FILE_FOLDER.getPath() + File.separator);
    }


    @Resource
    private AccessInterceptor accessInterceptor;

    /**
     * 拦截器
     *
     * @param registry 拦截器注册表
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(accessInterceptor)
                .addPathPatterns("/api/**")
                .excludePathPatterns(EXCLUDE_PATH_PATTERNS);
    }

    public static final String[] EXCLUDE_PATH_PATTERNS = new String[]{
            "/api/admin/**", "/api/file/**", "/api/msg/**", "/api/public/**"
    };

}
